package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.Cache;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        //1、组装Dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        if(dish.getStatus() == null){
            dish.setStatus(StatusConstant.ENABLE);
        }

        //2、调用mapper保存dish
        this.dishMapper.save(dish);

        //3、组装DishFlavor集合
        dishDTO.getFlavors().forEach(f -> f.setDishId(dish.getId()));

        //4、调用mapper保存dishFlavors
        dishFlavorMapper.batchSave(dishDTO.getFlavors());

        //5 clear cache
        String cacheKey = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(cacheKey);
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    @Cache(group = "dishpage",key="#dto.page,#dto.name,#dto.categoryId,#dto.status")
    public PageResult pageQuery(DishPageQueryDTO dto) {
        //1、PageHelper设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2、调用mapper进行分页条件查询
        Page<DishVO> page = this.dishMapper.pageQuery(dto);

        //3、封装PageResult并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        //1、先判断被删除的菜品中是否有菜品为启售状态，如果有，不能删除
        Integer count = this.dishMapper.countEnablesByIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //2、再判断被删除的菜品中有没有菜品被套餐关联，如果有，不能删除
        count = this.setmealMapper.countByDishIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3、删除菜品
        this.dishMapper.batchDelete(ids);

        //4、删除菜品关联的口味数据
        this.dishFlavorMapper.batchDeleteByDishIds(ids);

        //5 clear cache
        final Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据ID查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO queryById(Long id) {
        //1、根据id查询菜品
        DishVO dishVo = this.dishMapper.queryById(id);

        //2、根据id查询菜品口味
//        List<DishFlavor> dishFlavors = this.dishFlavorMapper.queryByDishId(id);

        //3、组装dishVO并返回
//        dishVo.setFlavors(dishFlavors);
        return dishVo;
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        //1、修改主表菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        this.dishMapper.update(dish);

        //2、删除从表菜品口味数据
        List<Long> ids = new ArrayList<>();
        ids.add(dish.getId());
        this.dishFlavorMapper.batchDeleteByDishIds(ids);

        //3、批量新增从表菜品口味数据
        dishDTO.getFlavors().forEach(f -> f.setDishId(dish.getId()));
        dishFlavorMapper.batchSave(dishDTO.getFlavors());

        //4 clear cache
        final DishVO dishVO = dishMapper.queryById(dishDTO.getId());
        String cacheKey = "dish_" + dishVO.getCategoryId();
        redisTemplate.delete(cacheKey);
        cacheKey = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(cacheKey);
    }

    /**
     * 启售停售
     *
     * @param id
     * @param status
     */
    @Override
    public void startOrStop(Long id, Integer status) {
        final Dish dish = Dish.builder().id(id).status(status).build();
        this.dishMapper.update(dish);

        //5 clear cache
        final Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }

    /**
     * 根据查询条件查询
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> list(Dish dish) {
        String cacheKey = "dish_" + dish.getCategoryId();
        //query cache dish by getCategoryId
        List<DishVO> dishVOS = (List<DishVO>)redisTemplate.opsForValue().get(cacheKey);
        if(ObjectUtils.isNotEmpty(dishVOS)){
            return dishVOS;
        }
        //add cache
        List<DishVO> dishVOList = dishMapper.list(dish);
        redisTemplate.opsForValue().set(cacheKey,dishVOList);
        return dishVOList;
    }
}
